﻿using System;
using System.Text;
using System.Diagnostics;

using Nextensions.Basic;

namespace Nextensions.WinApi
{
	public class CommandPipe
	{
		private StringBuilder _outputText;
		private StringBuilder _errorText;

		public OperationResult<string> Execute(string file, string arguments)
		{
			return Execute(file, arguments, null);
		}

		public OperationResult<string> Execute(string file, string arguments, string workingDirectory)
		{
			Process process = new Process();

			_outputText = new StringBuilder();
			_errorText = new StringBuilder();
			process.ErrorDataReceived += process_ErrorDataReceived;
			process.OutputDataReceived += process_OutputDataReceived;
			process.StartInfo.UseShellExecute = false;
			process.StartInfo.RedirectStandardError = true;
			process.StartInfo.RedirectStandardInput = true;
			process.StartInfo.RedirectStandardOutput = true;
			process.StartInfo.FileName = file;
			process.StartInfo.Arguments = arguments;
			process.StartInfo.CreateNoWindow = true;
			//process.StartInfo.WindowStyle

			if (workingDirectory != null)
				process.StartInfo.WorkingDirectory = workingDirectory;

			try
			{
				process.Start();
				process.BeginOutputReadLine();
				process.BeginErrorReadLine();
				process.WaitForExit();
			}
			catch (Exception ex)
			{
				return new OperationResult<string>(ex);
			}

			if (_errorText.Length > 0)
			{
				return new OperationResult<string>(new Exception(_errorText.ToString()));
			}
			else
			{
				return new OperationResult<string>(true, _outputText.ToString());
			}
		}

		private void process_OutputDataReceived(object sender, DataReceivedEventArgs e)
		{
			if (e.Data == null)
				return;
			
			_outputText.AppendFormat("{0}\r\n", e.Data);
		}

		private void process_ErrorDataReceived(object sender, DataReceivedEventArgs e)
		{
			if (e.Data == null)
				return;

			_errorText.AppendFormat("{0}\r\n", e.Data);
		}
	}
}
